import { Component, OnInit, Input, ChangeDetectionStrategy, Output, OnChanges, SimpleChanges, EventEmitter } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-wyy-verify-code',
  templateUrl: './wyy-verify-code.component.html',
  styleUrls: ['./wyy-verify-code.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class WyyVerifyCodeComponent implements OnInit, OnChanges {
  formModel: FormGroup;
  phoneStr = '';
  showRepeat = false;
  showErrorTip = false;
  @Input() phoneNumber: string;
  @Input() codePass = false;
  @Input() timing: number;
  @Output() onCheckCode = new EventEmitter<string>();
  @Output() onReSendCode = new EventEmitter<void>();
  @Output() onCheckExist = new EventEmitter<void>();
    constructor(private fb: FormBuilder) {
    this.formModel = this.fb.group({
      code: new FormControl('', [Validators.required, Validators.pattern(/\d{4}/)])
    });
    const codeControl = this.formModel.get('code');
    codeControl.statusChanges.subscribe(status => {
      if (status === 'VALID') {
        this.onCheckCode.emit(this.formModel.value.code);
      }
    });
  }
  @Input ()
  set phone(phone: string) {
    const arr = phone && (phone.split(''));
    arr.splice(3, 4, '****');
    this.phoneStr = arr.join('');
  }
  get phone(): string {
    return this.phoneStr;
  }
  ngOnInit() {
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.timing) {
      if (this.timing <= 0) {
        this.showRepeat = true;
      }
    }
    if (changes.codePass && !changes.codePass.firstChange) {
      this.showErrorTip = !this.codePass;
    }
  }
  reSendSmsCode() {
    this.showRepeat = false;
    this.onReSendCode.emit();
  }
  onSubmit() {
    if (this.formModel.valid && this.codePass) {
      this.onCheckExist.emit();
    }
  }
}
